package com.pig4cloud.pig.ads.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pig4cloud.pig.ads.service.AdUserAdverService;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.ads.service.TtInterestActionService;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.api.entity.ResponseArrayBean;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class TtInterestActionServiceImpl implements TtInterestActionService {

	@Autowired
	private AdUserAdverService adUserAdverService;

	@Autowired
	private TtAccesstokenService ttAccesstokenService;

	@Autowired
	private AdvService advService;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Value("${interest_action_url_tt}")
	private String interestActionUrlTt;

	/**
	 * 此接口错误率较高，做了特殊的查询，最多查询三次
	 * @param actionDays
	 * @param actionScene
	 * @return
	 */
	@Override
	public R getActionCategory(Integer actionDays, String actionScene) {
		String url = interestActionUrlTt + "action/category/";
		int i = 0;
		JSONArray arr = null;
		while (i < 3) {
			i++;
			try {
				arr = actionCategory(url, actionDays, actionScene);
				if (arr != null) {
					return R.ok(arr, "获取成功");
				}
			} catch (Throwable e) {
				log.error("拉取行为类目查询失败次数={}", i);
			}
		}
		return R.failed("第三方调用失败");
	}

	private JSONArray actionCategory(String url, Integer actionDays, String actionScene) throws Exception{
		String advertiserId = this.randomAdvertiserId();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("advertiser_id", advertiserId);
		data.put("action_days", actionDays);
		data.put("action_scene", actionScene.split(","));

		String token = ttAccesstokenService.fetchAccesstoken(advertiserId);
		//调用头条接口
		String resultStr = OEHttpUtils.doGet( url, data, token);
		//log.info("====>行为类目查询resultStr:{}", resultStr);
		ResponseArrayBean resBean = JSON.parseObject(resultStr, ResponseArrayBean.class);
		if(resBean != null && "0".equals(resBean.getCode())){
			JSONArray jsonObj = resBean.getData();
			return jsonObj;
		}else{
			return null;
		}
	}

	@Override
	public R getActionKeyword(Integer actionDays, String actionScene) {
		String advertiserId = this.randomAdvertiserId();

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("advertiser_id", advertiserId);
		data.put("action_days", actionDays);
		data.put("action_scene", actionScene.split(","));

		String token = ttAccesstokenService.fetchAccesstoken(advertiserId);			//this.getAccesstoken(advertiserId);

		//调用头条接口
		String resultStr = OEHttpUtils.doGet(interestActionUrlTt + "action/keyword/", data, token);

		//结果为null，当做失败
		if (StringUtils.isBlank(resultStr))
			return R.failed("从toutiao获取失败:resultStr is blank");

		JSONObject obj = JSON.parseObject(resultStr);
		if (!obj.getInteger("code").equals(0)){	//同步失败
			return R.failed("从toutiao获取失败:" + obj.getString("message"));
		}else{
			JSONArray arr = obj.getJSONObject("data").getJSONArray("list");
			return R.ok(arr, "获取成功");
		}
	}

	@Override
	public R getInterestCategory() {
		String advertiserId = this.randomAdvertiserId();

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("advertiser_id", advertiserId);

		String token = ttAccesstokenService.fetchAccesstoken(advertiserId);			//this.getAccesstoken(advertiserId);
		//String token01 = "64687195c4fb99c52066a06fc7ddddd4b24e65ac";

		//调用头条接口
		String resultStr = OEHttpUtils.doGet( interestActionUrlTt + "interest/category/", data, token);

		//结果为null，当做失败
		if (StringUtils.isBlank(resultStr))
			return R.failed("从toutiao获取失败:resultStr is blank");

		JSONObject obj = JSON.parseObject(resultStr);
		if (!obj.getInteger("code").equals(0)){	//同步失败
			return R.failed("从toutiao获取失败:" + obj.getString("message"));
		}else{
			JSONArray arr = obj.getJSONArray("data");
			return R.ok(arr, "获取成功");
		}
	}

	@Override
	public R getInterestKeyword() {
		String advertiserId = this.randomAdvertiserId();

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("advertiser_id", advertiserId);
		data.put("id","0");
		data.put("tag_type", "CATEGORY");
		data.put("targeting_type","INTEREST");

		String token = ttAccesstokenService.fetchAccesstoken(advertiserId);			//this.getAccesstoken(advertiserId);
		//token = "64687195c4fb99c52066a06fc7ddddd4b24e65ac";

		//调用头条接口
		String resultStr = OEHttpUtils.doGet( interestActionUrlTt + "keyword/suggest/", data, token);

		//结果为null，当做失败
		if (StringUtils.isBlank(resultStr))
			return R.failed("从toutiao获取失败:resultStr is blank");

		JSONObject obj = JSON.parseObject(resultStr);
		if (!obj.getInteger("code").equals(0)){	//同步失败
			return R.failed("从toutiao获取失败:" + obj.getString("message"));
		}else{
			JSONArray arr = obj.getJSONObject("data").getJSONArray("list");
			return R.ok(arr, "获取成功");
		}
	}

	private String randomAdvertiserId(){
		PigUser user = SecurityUtils.getUser();
		if (user == null )
			return null;

		Integer id =  user.getId();
		//获取当前账号下 广告账户列表
		List<String> adAccountList = advService.getOwnerAdv(id, PlatformTypeEnum.TT.getValue());
		if(adAccountList == null || adAccountList.size() == 0) {
			return null;
		}

		return adAccountList.get(0);
	}
}
